﻿using Bot.Domain.Conversation;
using Bot.Domain.SessionChat;



using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bot.Domain.Report
{
    public class Last7DaysDailyItem : BaseReportInfoItem
    {
        public int ChatBotOnly { get; set; }
        public int FromBotToAgent { get; set; }
        public int DailyChatsCount { get; set; }
        public double PercentageOfBotOnlyChats { get; set; }

        public override string GetValue(int i)
        {
            switch (i)
            {
                case 0:
                    return this.DailyChatsCount.ToString();
                    break;
                case 1:
                    return this.ChatBotOnly.ToString();
                    break;
                case 2:
                    return this.FromBotToAgent.ToString();
                    break;
                case 3:
                    return this.PercentageOfBotOnlyChats.ToString();
                    break;
                default:
                    return "";
            }
        }
    }
    public class Last7DaysDailyInfo : BaseReportInfo<Last7DaysDailyItem>
    {
        [JsonIgnore]
        public double TotalChats { get; set; }
        public int TotalChatbotOnly { get; set; }
        public int TotalFromBotToAgent { get; set; }
        [JsonIgnore]
        public double TotalAgentOnly { get; set; }
        public double TotalPercentageOfBotOnlyChats { get; set; }

        [JsonIgnore]
        public override List<string> FieldList
        {
            get
            {
                return new List<string>() {
                    "Total Chats","Bot Only","From Bot To Agent","Percentage Of Bot Only Chats"
                };
            }
        }
        public override string GetValue(int i)
        {
            switch (i)
            {
                case 0:
                    return this.TotalChats.ToString();
                    break;
                case 1:
                    return this.TotalChatbotOnly.ToString();
                    break;
                case 2:
                    return this.TotalFromBotToAgent.ToString();
                    break;
                case 3:
                    return this.TotalPercentageOfBotOnlyChats.ToString();
                    break;               
                default:
                    return "";
            }
        }
    }
    public class Last7DaysDailyEntityInfo
    {
        public IList<SessionChatDto> Last7DaysDailyEntityList { get; set; }
        public List<ConversationDto> ConversationList { get; set; }
    }

    public class Last7DaysDailyWrap : BasicWrap<Last7DaysDailyItem, Last7DaysDailyInfo, Last7DaysDailyEntityInfo>
    {
        
        public static Last7DaysDailyInfo GetLast7DaysDaily(SearchCriteria search, Last7DaysDailyEntityInfo entityInfo, bool ifEncode = true)
        {
            //System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            //watch.Start();

            //Last7DaysDailyourceEntityInfo entityInfo = Last7DaysDailyourceProcess.GetLast7DaysDailyourceData(search); //数据库查询出来的数据

            //System.Diagnostics.Debug.WriteLine("Access Time: " + watch.Elapsed);
            //watch.Reset();
            //watch.Start();
            //System.Diagnostics.Debug.WriteLine(entityInfo.Last7DaysDailyourceEntityList.Count);
            //System.Diagnostics.Debug.WriteLine(entityInfo.Last7DaysDailyourceNumEntityList.Count);

            Last7DaysDailyInfo result = new Last7DaysDailyInfo();
            //UTCToLocal(ref entityInfo);
            switch (search.dimensionType)
            {
                case EnumDimensionType.ByTime://by time
                    result = GetInfoByTime(search, entityInfo, PushByTimeData, null, null);
                    break;
            }

            //watch.Stop();
            //System.Diagnostics.Debug.WriteLine("Calc Time: " + watch.Elapsed);

            return result;
        }

        private static Last7DaysDailyInfo PushByTimeData(Last7DaysDailyInfo result, Last7DaysDailyEntityInfo entityInfo, SearchCriteria search)
        {
            if(search.SummaryChannel == "livechat")
            {
                IEnumerable<SessionChatDto> Last7DaysDailyEntityList = entityInfo.Last7DaysDailyEntityList.OrderBy(c => c.RequestTime);

                int[] onlyBotStatus = new int[] { 0, 1, 2 };
                foreach (Last7DaysDailyItem chatitem in result.dataList)
                {
                    List<SessionChatDto> todayChatsEntityList = Last7DaysDailyEntityList.Where(a => Today(chatitem, a.RequestTime, search.timeOffset)).ToList();

                    double agentOnlyCount = todayChatsEntityList.Count(a => a.Status == 0 && a.ChatType == (int)EnumChatType.AgentOnly);
                    chatitem.ChatBotOnly = todayChatsEntityList.Count(a => onlyBotStatus.Contains(a.Status) && a.ChatType == (int)EnumChatType.ChatbotOnly);
                    chatitem.FromBotToAgent = todayChatsEntityList.Count(a => a.Status == 0 && a.ChatType == (int)EnumChatType.ChatbotToAgent);
                    chatitem.DailyChatsCount = (int)(agentOnlyCount + chatitem.ChatBotOnly + chatitem.FromBotToAgent);

                    result.TotalChatbotOnly += chatitem.ChatBotOnly;
                    result.TotalFromBotToAgent += chatitem.FromBotToAgent;


                    result.TotalChats += chatitem.DailyChatsCount;
                }
            }
            else
            {
                IEnumerable<ConversationDto> Last7DaysDailyEntityList = entityInfo.ConversationList.OrderBy(c => c.CreatedTime);

                foreach (Last7DaysDailyItem chatitem in result.dataList)
                {
                    List<ConversationDto> todayChatsEntityList = Last7DaysDailyEntityList.Where(a => Today(chatitem, a.CreatedTime, search.timeOffset)).ToList();

                    double agentOnlyCount = 0;
                    chatitem.ChatBotOnly = todayChatsEntityList.Count(a => a.AssignedBotId != Guid.Empty && a.AssignedAgentId == Guid.Empty && a.AssignedDepartmentId == Guid.Empty);
                    chatitem.FromBotToAgent = todayChatsEntityList.Count(a => a.AssignedBotId != Guid.Empty && (a.AssignedAgentId != Guid.Empty || a.AssignedDepartmentId != Guid.Empty));
                    chatitem.DailyChatsCount = todayChatsEntityList.Count();

                    result.TotalChatbotOnly += chatitem.ChatBotOnly;
                    result.TotalFromBotToAgent += chatitem.FromBotToAgent;


                    result.TotalChats += chatitem.DailyChatsCount;
                }
            }            

            //int lindex = 0;
            //foreach (var item in Last7DaysDailyEntityList)
            //{
            //    item.RequestTime = DateTimeHelper.UTCToLocal(item.RequestTime); 

            //    Last7DaysDailyItem chatitem = result.dataList[lindex];
            //    while (item.RequestTime >= chatitem.endTimeDate && lindex < result.dataList.Count)
            //    {
            //        lindex++;
            //        chatitem = result.dataList[lindex];
            //    }
            //    chatitem.DailyChatsCount++;
            //    result.TotalChats++;
            //    switch (item.ChatType)
            //    {
            //        case (int)EnumChatType.AgentOnly:     
            //            result.TotalAgentOnly++;
            //            break;
            //        case (int)EnumChatType.ChatbotOnly:
            //            chatitem.BotOnlyChatsCount++;
            //            result.TotalChatbotOnly++;
            //            break;
            //        case (int)EnumChatType.ChatbotToAgent:
            //            chatitem.ChatsFromBotToAgentCount++;
            //            result.TotalFromBotToAgent++;
            //            break;
            //        default:
            //            break;
            //    }
            //}

            foreach (Last7DaysDailyItem item in result.dataList)
            {
                item.tableRowName = item.xAxisName;
                item.PercentageOfBotOnlyChats = CalcAvg(item.ChatBotOnly*100 , item.DailyChatsCount);
            }
            result.dataList = result.dataList.Reverse().ToList();
            GetListTotal(ref result, search);
            return result;
        }
        private static bool Today(Last7DaysDailyItem chatsItem, DateTime utcDate,TimeSpan timeOffset)
        {
            Guid operatorId = Guid.Empty;
            operatorId = SessionHelper.GetSessionValue_CurrentOperatorId();
            DateTime localDate = DateTimeHelper.UtcToLocal(utcDate, operatorId);
            return localDate >= chatsItem.startTimeDate && localDate < chatsItem.endTimeDate;
        }
        private static void GetListTotal(ref Last7DaysDailyInfo result, SearchCriteria search)
        {
            //对数据进行格式化的，取小数位2，平均值

            double divNum = 0;
            if (search.timeUnit == EnumTimeIntervalType.Distribution24_7Hour)
            {
                divNum = GetWeeksInDateRange(search.startDate, search.endDate);
            }
            else if (search.timeUnit == EnumTimeIntervalType.Distribution48HalfHour)
            {
                divNum = GetDays(search.startDate, search.endDate);
            }
            else
            {
                result.TotalChats = CalcTwoPoint(result.TotalChats);
                result.TotalAgentOnly = CalcTwoPoint(result.TotalAgentOnly);
                result.TotalChatbotOnly = result.TotalChatbotOnly;
                result.TotalFromBotToAgent = result.TotalFromBotToAgent;
                result.TotalPercentageOfBotOnlyChats = CalcAvg(result.TotalChatbotOnly*100, result.TotalChats);
            }

            if (search.timeUnit == EnumTimeIntervalType.Distribution24_7Hour || search.timeUnit == EnumTimeIntervalType.Distribution48HalfHour)
            {
                result.TotalChats = CalcAvg(result.TotalChats, divNum);
                result.TotalAgentOnly = CalcAvg(result.TotalAgentOnly, divNum);
                result.TotalChatbotOnly = result.TotalChatbotOnly;
                result.TotalFromBotToAgent = result.TotalFromBotToAgent;
                result.TotalPercentageOfBotOnlyChats = CalcAvg(result.TotalChatbotOnly * 100, result.TotalChats);
            }
        }

        #region export

        //search the New Export CSV Data for Chat Source Info by criteria
        public static NewExportCSVData GetExprotData(SearchCriteria search, Last7DaysDailyEntityInfo entityInfo)
        {
            Last7DaysDailyInfo info = GetLast7DaysDaily(search, entityInfo, false);
            NewExportCSVData result = new NewExportCSVData(string.Empty, new List<NewCSVColumn>(), new DataTable());
            switch (search.dimensionType)
            {
                case EnumDimensionType.ByTime://by time
                case EnumDimensionType.ByDepartment://by department
                case EnumDimensionType.ChatbotChats://by department
                case EnumDimensionType.ChatbotAnswers://by department
                case EnumDimensionType.ChatbotHightFidenceAnswers://by department
                    {
                        result = GetExprotCSVData(search, info, info.FieldList);
                        break;
                    }
                case EnumDimensionType.RequestPage:
                    {
                        result = GetExprotCSVData(search, info, new List<string>() { info.FieldList[0] });
                        break;
                    }
            }
            return result;
        }

        #endregion

    }
}
